package com.luming.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.luming.common.core.domain.R;
import com.luming.common.core.enums.ResultCode;
import com.luming.common.core.enums.UserIdentity;
import com.luming.common.redis.service.RedisService;
import com.luming.common.security.service.TokenService;
import com.luming.system.domain.SysUser;
import com.luming.system.mapper.SysUserMapper;
import com.luming.system.service.ISysUserService;
import com.luming.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;


/**
 * @Author Luming
 * @Date 2024/8/23 20:26
 * @Description:
 */
@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private TokenService tokenService;
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Override
    public R<String> login(String userAccount, String password) {
        //通过账号去数据库中查询对应用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_sys_user where user_account = #{userAccount}
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper.
                select(SysUser::getUserId, SysUser::getPassword).eq(SysUser::getUserAccount, userAccount));
        if (sysUser == null) {
            //用户不存在
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            //登录成功,调用TokenService生成Token并且返回给前端
            return R.ok(tokenService.creatToken(sysUser.getUserId(), secret, UserIdentity.ADMIN.getValue()));
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }
}
